import 'dart:io';
import 'dart:math';

import 'package:camera/camera.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';

import '../../../common/api/x_ali_face_detection_assemble_control.dart';
import '../../../common/models/ali_face/index.dart';
import '../../../common/utils/loading.dart';
import '../../../common/utils/log_util.dart';
import '../../../common/widgets/o2_stateless_widget.dart';
import 'index.dart';

class FaceCheckPageController extends GetxController
    with GetSingleTickerProviderStateMixin {
  FaceCheckPageController();

  late AnimationController animationController;
  late Animation<double> animation;
  late CameraController _cameraController;
  late List<CameraDescription> _cameras;
  final state = FaceCheckPageState();
  final GlobalKey cameraPreviewKey = GlobalKey();

  FaceCheckPageMode mode = FaceCheckPageMode.faceDetection;

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    final args = Get.arguments;
    if (args != null && args['mode'] != null) {
      state.mode.value = args['mode'] as FaceCheckPageMode;
    }
    checkMyFaceList();
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    animationController.dispose();
    if (_cameraController.value.isInitialized) {
      _cameraController.dispose();
    }
    super.onClose();
  }

  getCameraController() => _cameraController;

  /// 检查我的人脸列表
  Future<void> checkMyFaceList() async {
    final list =
        await AppAliFaceDetectionAssembleControlService.to.myFaceList();
    if (state.mode.value == FaceCheckPageMode.faceDetection) {
      if (list != null && list.isNotEmpty) {
        await _initUI();
        _startFaceDetection();
      } else {
        OLogger.d('message: 未注册人脸');
        _exitPage('common_ali_face_not_registration_message'.tr);
      }
    } else {
      if (list != null && list.isNotEmpty) {
        _exitPage('common_ali_face_already_registration_message'.tr);
      } else {
        _initUI();
      }
    }
  }

  /// 退出页面
  _exitPage(String message) {
    final context = Get.context;
    if (context != null) {
      O2UI.showAlert(context, message, okPressed: () => Get.back());
    } else {
      Loading.toast(message);
      Get.back();
    }
  }

  /// 初始化 UI
  Future<void> _initUI() async {
    initAnimation();
    await initializeCamera();
  }

  /// 初始化 Animation
  void initAnimation() {
    animationController = AnimationController(
      vsync: this,
      duration: const Duration(seconds: 2),
    );
    // 设置 Tween 动画
    animation = Tween<double>(begin: 0.0, end: 1.0).animate(CurvedAnimation(
      parent: animationController,
      curve: Curves.easeInOut,
    ));
    // 开始动画
    animationController.repeat(reverse: true);
  }

  /// 初始化相机
  Future<void> initializeCamera() async {
    _cameras = await availableCameras();
    _cameraController = CameraController(
      _cameras.firstWhere(
          (camera) => camera.lensDirection == CameraLensDirection.front),
      ResolutionPreset.high,
    );
    await _cameraController.initialize();
    state.isCameraInitialized = true;
    OLogger.d('初始化相机完成， ${_cameraController.value.deviceOrientation}');
  }

  /// 缩放人脸识别区域
  changeScale(Size size) {
    final width = size.width;
    final height = size.height;
    if (width < height) {
      final minWidth = min(width, 240);
      state.scale = minWidth / width;
    } else {
      final minWidth = min(height, 240);
      state.scale = minWidth / height;
    }
    OLogger.d(' scale ====== ${state.scale}');
  }

  /// 拍照并上传
  Future<void> captureAndUploadPhoto() async {
    OLogger.d('message: 拍照并上传');
    if (_cameraController.value.isTakingPicture) {
      OLogger.e('message1: 正在拍照中');
      return;
    }
    try {
      final XFile file = await _cameraController.takePicture();
      Loading.show();
      final result = await AppAliFaceDetectionAssembleControlService.to
          .faceRegistration(File(file.path));
      if (result != null) {
        Loading.dismiss();
        OLogger.d('message: 上传成功');
        _exitPage('common_ali_face_registration_success'.tr);
      }
    } on CameraException catch (e) {
      Loading.toast('Error: ${e.code}\n${e.description}');
    }
  }

  /// 开始人脸检测
  int _detectionTimes = 0;

  Future<void> _startFaceDetection() async {
    // 重置检测次数
    _detectionTimes = 0;
    // 延迟开始
    var future = Future.delayed(const Duration(seconds: 1), () {
      return 1;
    });
    await future;
    while (_detectionTimes < 5) {
      OLogger.d('开始人脸检测， 第 $_detectionTimes 次');
      try {
        if (_cameraController.value.isTakingPicture) {
          OLogger.e('message: 正在拍照中');
          continue;
        }
        final XFile file = await _cameraController.takePicture();
        final result = await AppAliFaceDetectionAssembleControlService.to
            .faceCompare(File(file.path));
        if (result != null && result.value == true) {
          OLogger.d('message: 人脸检测成功');
          Get.back(result: FaceDetectionResult(result: true));
          return;
        }
        OLogger.d('人脸检测失败， ${result?.toJson()}');
      } on CameraException catch (e) {
        OLogger.e('Error: ${e.code}\n${e.description}');
      }
      // 延迟 1 秒后再次检测
      var future = Future.delayed(const Duration(milliseconds: 1500), () {
        return 1;
      });
      _detectionTimes += await future;
    }

    O2UI.showConfirm(
        Get.context, 'common_ali_face_detection_times_out_confirm'.tr,
        okPressed: () {
          _startFaceDetection();
        },
        cancelPressed: () => Get.back());
  }
}
